#include "putPackage.h"
#include "cJSON.h"
static const char *putMap[] = {"0","1","2","3","4","\n","5","6","7","8","9","\n",LV_SYMBOL_BACKSPACE,LV_SYMBOL_NEW_LINE,""};

void processPutJson(const char *str){
   
   cJSON*root=cJSON_CreateObject();

   cJSON_AddStringToObject(root,"boxName","xufei");
   cJSON_AddStringToObject(root,"phone",str);
   char*result=cJSON_PrintUnformatted(root);
   Serial.println(result);
   mqtt_Push("woniuSms",result);
   cJSON_Delete(root);
   free(result);

}

void btnmEvent_Put_handler(lv_event_t *e){
  int code = lv_event_get_code(e);
  lv_obj_t* target =  (lv_obj_t*)lv_event_get_target(e);//通过e获取到产生事件的控件
  lv_obj_t* textarea = (lv_obj_t*)lv_event_get_user_data(e);//获取到参数
  if(code ==LV_EVENT_VALUE_CHANGED){
      // 获取单击的按钮编号
    uint16_t index = lv_btnmatrix_get_selected_btn(target);
    Serial.println(index);
    // 获取单击的按钮文本获取到按键的文本内容，也就是上面定义的btnm map里面的内容，比如用户点了1按键，获取的就是1
    const char* btn_text = lv_btnmatrix_get_btn_text(target,index);
    Serial.println(btn_text);
    // 条件判断
    if(strcmp(btn_text,LV_SYMBOL_BACKSPACE) == 0){
      //Serial.println("back clicked");
      lv_textarea_del_char(textarea);
    }else if (strcmp(btn_text,LV_SYMBOL_NEW_LINE) == 0)
    {
      //Serial.println("enter clicked");
      lv_event_send(textarea, LV_EVENT_READY, NULL);//给文本域发送一个事件
    }else{
        // 向文本框中填入内
      lv_textarea_add_text(textarea,btn_text);
    }

  }

}
static void textarea_event_Put_handler(lv_event_t * e)
{
    lv_obj_t * ta = lv_event_get_target(e);
    lv_obj_t* textarea = (lv_obj_t*)lv_event_get_user_data(e);
    processPutJson(lv_textarea_get_text(ta));
    lv_textarea_set_text(textarea,"");

    //Serial.printf("Enter was pressed. The current text is: %s\n", lv_textarea_get_text(ta));
}


void createPutPackage(lv_obj_t *tab){

  // 文本框
    lv_obj_t* textarea = lv_textarea_create(tab);

    lv_textarea_set_one_line(textarea,true);//不允许换行
    lv_obj_align(textarea,LV_ALIGN_TOP_MID,0,10);
    lv_obj_set_width(textarea,270);
    lv_obj_add_state(textarea, LV_STATE_FOCUSED);//让光标放在输入框上
    lv_obj_set_style_bg_color(textarea,lv_color_make(143,123,53),0);
    lv_textarea_set_placeholder_text(textarea,"请输入手机号");
    lv_obj_clear_flag(textarea,LV_OBJ_FLAG_CLICK_FOCUSABLE);//点击其他地方 光标不丢失
    lv_obj_add_event_cb(textarea, textarea_event_Put_handler, LV_EVENT_READY, textarea);
    // 创建矩阵按钮
    lv_obj_t* btnm = lv_btnmatrix_create(tab);
    // 设置矩阵按钮的显示
    lv_btnmatrix_set_map(btnm,putMap);
    lv_obj_set_width(btnm,270);
    lv_obj_set_height(btnm,200);
    lv_obj_align(btnm,LV_ALIGN_CENTER,0,50);
    lv_obj_clear_flag(btnm, LV_OBJ_FLAG_CLICK_FOCUSABLE);
    lv_obj_set_style_bg_color(btnm,lv_color_make(123,45,34),0);
    lv_obj_add_event_cb(btnm,btnmEvent_Put_handler,LV_EVENT_VALUE_CHANGED,textarea);
    lv_obj_set_style_text_font(btnm,&lv_font_montserrat_14,0);

}